<template>
	<view class="delivery-container">
		<!-- 顶部状态栏 -->
		<view class="status-bar">
			<view class="status-item" :class="{active: currentTab === 'available'}" @click="switchTab('available')">
				新配送订单({{availableOrders.length}})
			</view>
			<view class="status-item" :class="{active: currentTab === 'accepted'}" @click="switchTab('accepted')">
				待派送({{acceptedOrders.length}})
			</view>
		</view>

		<!-- 可接单订单列表 -->
		<scroll-view class="order-list" scroll-y>
			<view v-if="currentTab === 'available'">
				<view v-for="order in availableOrders" :key="order.id" class="order-card">
					<view class="order-header">
						<text class="order-id">订单号: {{order.orderNo}}</text>
						<text class="order-time">{{order.createTime}}</text>
					</view>
					<view class="order-info">
						<view class="info-item">
							<text class="label">收货人:</text>
							<text class="value">{{order.receiverName}}</text>
						</view>
						<view class="info-item">
							<text class="label">收货电话:</text>
							<text class="value">{{order.receiverPhone}}</text>
						</view>
						<view class="info-item">
							<text class="label">送餐点:</text>
							<text class="value">{{order.receiverAddress}}</text>
						</view>
						<view class="info-item">
							<text class="label">送达时间:</text>
							<text class="value">{{timeSlots(order.estimatedDeliveryTime)}}</text>
						</view>
						<view class="info-item">
							<text class="label">配送费:</text>
							<text class="value price">¥{{order.freightAmount}}</text>
						</view>
						<view class="info-item">
							<text class="label">备注:</text>
							<text class="value">{{order.remark ||""}}</text>
						</view>
					</view>
					<button class="accept-btn" @click="acceptOrder(order)">接单</button>
				</view>
			</view>

			<view v-else>
				<view v-for="order in acceptedOrders" :key="order.id" class="order-card">
					<view class="order-header">
						<text class="order-id">订单号: {{order.orderNo}}</text>
						<text class="order-status">{{getStatusText(order.orderStatus)}}</text>
					</view>
					<view class="order-info">
						<view class="info-item">
							<text class="label">收货人:</text>
							<text class="value">{{order.receiverName}}</text>
						</view>
						<view class="info-item">
							<text class="label">收货电话:</text>
							<text class="value">{{order.receiverPhone}}</text>
						</view>
						<view class="info-item">
							<text class="label">送餐点:</text>
							<text class="value">{{order.receiverAddress}}</text>
						</view>
						<view class="info-item">
							<text class="label">预达时间</text>
							<text
								class="value">{{timeSlots(order.estimatedDeliveryTime)}}</text>
						</view>
						<view class="info-item">
							<text class="label">配送费:</text>
							<text class="value price">¥{{order.freightAmount}}</text>
						</view>
						<view class="info-item">
							<text class="label">备注:</text>
							<text class="value">{{order.remark ||""}}</text>
						</view>
					</view>

					<view class="action-buttons">
						<button v-if="order.orderStatus === 3" class="action-btn qh"
							@click="pickOrder(order, '4')">取餐</button>
						<button v-if="order.orderStatus === 4" class="action-btn sd"
							@click="finishOrder(order, '5')">送达</button>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部导航 -->
		<view class="tab-bar">
			<view class="tab-item active">
				<uni-icons type="cart" size="24"></uni-icons>
				<text>接单</text>
			</view>
			<view class="tab-item" @click="navigateToStats">
				<uni-icons type="stats" size="24"></uni-icons>
				<text>统计</text>
			</view>
			<!--  <view class="tab-item" @click="navigateToProfile">
        <uni-icons type="person" size="24"></uni-icons>
        <text>我的</text>
      </view> -->
		</view>
	</view>
</template>

<script>
	import {
		getDeliveryList,
		getReceivedList,
		acceptOrder,
		pickOrder,
		finishOrder
	} from '@/api/system/orders.js'

	export default {
		data() {
			return {
				availableOrders: [], //可以接单
				currentTab: 'available',
				acceptedOrders: [], //已经接单
			}
		},
		onLoad() {
			this.deliveryList()
			this.receivedList()
		},

		methods: {
			// 获取可接单列表
			deliveryList() {
				getDeliveryList().then(res => {
					console.log("可接ps:", res.data);
					this.availableOrders = res.data
				})
			},
			// 获取已接单列表
			receivedList() {
				getReceivedList().then(res => {
					console.log("已接ps:", res.data);
					this.acceptedOrders = res.data
				})
			},
			// 切换
			switchTab(tab) {
				this.currentTab = tab
				if (tab === 'available') { // 当上面传available过来时需要调用可以接单列表查询的方法
					this.deliveryList()
				} else {
					// 否则调用已经接单的方法
					this.receivedList()
				}
			},
			//接单
			acceptOrder(order) {
				uni.showModal({
					title: '确认接单',
					content: `确认接取订单 ${order.orderNo} 吗？`,
					success: (res) => {
						if (res.confirm) { // 点击确认
							// 调用接口接单
							acceptOrder(order.id).then(res => {
								uni.showToast({
									title: '接单成功',
									icon: 'success'
								})
								this.deliveryList()
								this.receivedList()
							})
						} else {
							// 点击取消
						}
					}
				})
			},
			pickOrder(order, status) {
				uni.showModal({
					title: '确认接单',
					content: `确认到达取货点取货吗？`,
					success: (res) => {
						if (res.confirm) { // 点击确认
							pickOrder(order.id).then(res => {
								uni.showToast({
									title: '订单已取货',
									icon: 'success'
								})
								this.receivedList()
							})
						} else {
							// 点击取消
						}
					}
				})
			},

			finishOrder(order, status) {
				uni.showModal({
					title: '确认接单',
					content: `确认到达收货地址吗？`,
					success: (res) => {
						if (res.confirm) { // 点击确认
							finishOrder(order.id).then(res => {
								uni.showToast({
									title: '订单已完成',
									icon: 'success'
								})
								this.receivedList()
							})
						} else {
							// 点击取消
						}
					}
				})
			},

			getStatusText(status) {
				console.log(status);
				const statusMap = {
					'3': '已接单',
					'4': '已取餐',
					'5': '已完成'
				}
				return statusMap[status] || status
			},
			// 初始化时间段选择器
			timeSlots(timeString) {
			    // 将时间字符串转换为Date对象
			    const time = new Date(timeString);		    
			    // 计算开始时间（直接使用传入的时间）
			    const start = new Date(time);			    
			    // 计算结束时间（开始时间 + 15分钟）
			    const end = new Date(start.getTime() + 15 * 60 * 1000);    
			    // 格式化为时间段字符串
			    return `${this.formatTime(start)}-${this.formatTime(end)}`;
			},
			 
			// 格式化时间为 HH:mm
			formatTime(date) {
			    const hours = date.getHours().toString().padStart(2, '0');
			    const minutes = date.getMinutes().toString().padStart(2, '0');
			    return `${hours}:${minutes}`;
			},

			navigateToStats() {
				uni.showToast({
					title: '前往统计页面',
					icon: 'none'
				})
				// 实际开发中取消注释
				// uni.navigateTo({
				//   url: '/pages/stats/index'
				// })
			},
			navigateToProfile() {
				uni.showToast({
					title: '前往个人中心',
					icon: 'none'
				})
				// 实际开发中取消注释
				// uni.navigateTo({
				//   url: '/pages/profile/index'
				// })
			}
		}
	}
</script>

<style lang="scss">
	.delivery-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.status-bar {
		display: flex;
		background-color: #fff;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;

		.status-item {
			flex: 1;
			text-align: center;
			font-size: 28rpx;
			color: #666;

			&.active {
				color: #07c160;
				font-weight: bold;
				position: relative;

				&::after {
					content: '';
					position: absolute;
					bottom: -20rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 80rpx;
					height: 6rpx;
					background-color: #07c160;
					border-radius: 3rpx;
				}
			}
		}
	}

	.order-list {
		flex: 1;
		padding: 20rpx;
	}

	.order-card {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);

		.order-header {
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;
			font-size: 24rpx;
			color: #999;
		}

		.order-info {
			margin-bottom: 20rpx;

			.info-item {
				display: flex;
				margin-bottom: 10rpx;
				font-size: 26rpx;

				.label {
					color: #666;
					width: 120rpx;
				}

				.value {
					flex: 1;
					color: #333;
				}

				.price {
					color: #ff5f15;
					font-weight: bold;
				}
			}
		}

		.accept-btn {
			background-color: #07c160;
			color: #fff;
			border-radius: 40rpx;
			font-size: 28rpx;
			height: 70rpx;
			line-height: 70rpx;

			&:active {
				opacity: 0.8;
			}
		}

		.action-buttons {
			display: flex;
			justify-content: space-between;

			.action-btn {
				flex: 1;
				margin: 0 10rpx;
				height: 70rpx;
				line-height: 70rpx;
				font-size: 28rpx;
				border-radius: 40rpx;

				&:active {
					opacity: 0.8;
				}
			}

			.qh {
				background-color: #ffa500;
				color: #fff;
			}

			.sd {
				background-color: #07c160;
				color: #fff;
			}
		}

		.completed {
			text-align: center;
			color: #07c160;
			font-size: 28rpx;
			padding: 20rpx 0;
		}
	}

	.tab-bar {
		display: flex;
		background-color: #fff;
		border-top: 1rpx solid #eee;
		padding: 10rpx 0;

		.tab-item {
			flex: 1;
			text-align: center;
			font-size: 20rpx;
			color: #666;

			&.active {
				color: #07c160;
			}

			.uni-icons {
				display: block;
				margin: 0 auto 5rpx;
			}
		}
	}
</style>